//
//  CZLoginViewController.swift
//  weibo24
//
//  Created by 李文峰 on 16/2/27.
//  Copyright © 2016年 fengten. All rights reserved.
//

import UIKit
import AFNetworking
class CZLoginViewController: UIViewController ,UIWebViewDelegate{

    //创建一网页 填充整个界面
    var webView : UIWebView?
    
    
    override func loadView() {
        //不调用父类方法, 由服务器提供排布
        //创建实例
        webView = UIWebView()
        //代理
        webView?.delegate = self
        //赋值
        view = webView
        
        print(view)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //发出请求
        //获取url
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APP_KEY)&redirect_uri=\(APP_URL)&response_type=code")
        //创建请求
        let request = NSURLRequest(URL: url!)
        //加载请求
        webView?.loadRequest(request)
        
        //设置navigationItem
        setupNav()
    }


    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
    }
    //返回按钮点击事件
    func dismiss(){
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    //自动填充事件
    func auto(){
        
        let js = "document.getElementById(\"userId\").value = \"sun_wenfengli@sina.com\";document.getElementById(\"passwd\").value = \"liwenfeng\";"
        //注入到web页面
        
        webView?.stringByEvaluatingJavaScriptFromString(js)
  
    
    }

}



//UIWebViewDelegate代理方法
extension CZLoginViewController{
    
    func webViewDidStartLoad(webView: UIWebView) {
        
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //request.URL?.absoluteString绝对路径  转化成string
        
        
        print(request.URL?.absoluteString)
        
        
        //获取code  code=   
        //判断request.URL?.absoluteString有值
        if let url = request.URL?.absoluteString{
            // 前缀 -- url.hasPrefix(<#T##prefix: String##String#>)
            // 后缀 -- url.hasSuffix(<#T##suffix: String##String#>)
            //Optional("http://baidu.com/?code=47d08b6d35f82494ba3b2dc4de3dd062")
            //前缀和APP_URL相同
            if  url.hasPrefix(APP_URL){
                
                if let code = request.URL?.query{
                    print(code)
                    
                    
                    let subCode = code.substringFromIndex("code=".endIndex)
                    print(subCode)
//                    loadToken(subCode)
                  CZUserViewModel().loadToken(subCode, success: { () -> () in
                    print("成功")
                    
                    //<通知中心 ,发送通知>
                     NSNotificationCenter.defaultCenter().postNotificationName("nameVC", object: nil)
                    
//                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    
//                    })
                    
                    }, failure: { () -> () in
                        print("失败")
                  })
//                    let userViewModel: CZUserViewModel = CZUserViewModel()
//                    
//                    userViewModel.loadToken(subCode)
                    
                    return false
                }
                
            }
        }
        
        
        
        
//   Optional("https://api.weibo.com/oauth2/authorize?client_id=2767424124&redirect_uri=1ddae4677d56568a31b4df8b1751e2ca&response_type=code")
        return true
    }
    
    
}

//通过csde获取token

    

    

